package minio_client

import (
	"context"
	"fmt"
	"mime/multipart"
	"strings"

	"github.com/blog-zero/api/admin/internal/config"
	"github.com/blog-zero/api/admin/internal/types"
	"github.com/blog-zero/common/libs"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type MinioClient struct {
	BucketName    string
	MinioClient   *minio.Client
	AccessBaseUrl string
}

func NewMinioClient(conf *config.Config) (*MinioClient, error) {
	cfg := conf.Minio
	minioClient, err := minio.New(cfg.Address, &minio.Options{
		Creds:  credentials.NewStaticV4(cfg.Ak, cfg.Sk, ""),
		Secure: false,
	})
	if err != nil {
		logx.Error("new minio client error" + err.Error())
		return nil, err
	}
	return &MinioClient{
		MinioClient:   minioClient,
		BucketName:    cfg.Bucket,
		AccessBaseUrl: cfg.AccessBaseUrl,
	}, nil
}

// UploadFile 上传文件
func (c *MinioClient) UploadFile(ctx context.Context, file *multipart.FileHeader, contentType string) (string, error) {
	fileName := file.Filename
	if strings.Contains(fileName, ".") {
		fileNameArr := strings.Split(fileName, ".")
		file.Filename = string(libs.RandStr(10, libs.Numbers)) + "." + fileNameArr[len(fileNameArr)-1]
	} else {
		file.Filename = string(libs.RandStr(10, libs.Numbers))
	}
	logc.Errorf(ctx, "file.Filename:===========>%s", file.Filename)
	fileReader, err := file.Open()
	if err != nil {
		return "", err
	}
	_, err = c.MinioClient.PutObject(ctx, c.BucketName, file.Filename, fileReader, file.Size, minio.PutObjectOptions{
		ContentType: contentType,
	})
	if err != nil {
		return "", err
	}

	//http://127.0.0.1:9000/bsite/mange2.png
	return fmt.Sprintf("/%s/%s", c.BucketName, file.Filename), nil
}

// UploadFile 上传文件
func (c *MinioClient) UploadFileList(ctx context.Context, inputs map[*multipart.FileHeader]string) ([]*types.UploadFileList, error) {
	var urls []*types.UploadFileList
	for file, contentType := range inputs {
		url, err1 := c.UploadFile(ctx, file, contentType)
		if err1 != nil {
			logc.Errorf(ctx, "上传minio失败,异常:%s", err1.Error())
			return nil, err1
		}
		item := &types.UploadFileList{
			Url:  url,
			Type: contentType,
		}
		urls = append(urls, item)
	}
	//http://127.0.0.1:9000/bsite/mange2.png
	return urls, nil
}
